package com.advice;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class AdviceTest {

	// 匹配com.abc.service下的类中以before开始的方法

	@Before("execution(*  com.service.*.*Advice(..))")
	public void beforeAdvice() {
		System.out.println("@Before增强");
	}
	
	@Before("execution(*  com.web.controller.*.login(..))")
	public void beforelogin() {
		System.out.println("@Before增强");
	}

	@AfterReturning(returning = "returnValue", pointcut = "execution(*  com.service.*.*Advice(..))")
	public void afterReturning(Object returnValue) {
		System.out.println("@AfterReturning增强");
		System.out.println("returnValue："+returnValue);
	}

	@AfterThrowing(throwing = "exception", pointcut = "execution(*  com.service.*.throwing*(..))")
	public void afterThrowing(Throwable exception) {
		System.out.println("@AfterThrowing增强");
		System.out.println("throwing："+exception);
	}

	@After("execution(* com.service.*.to*(..))")
	public void afterTo(JoinPoint point) {
		System.out.println("@After增强开始");
		System.out.println("@After：目标方法为："+point.getSignature().getDeclaringTypeName()+"."+point.getSignature().getName());
		System.out.println("@After：参数为："+Arrays.toString(point.getArgs()));
		System.out.println("@After：被织入的目标对象为："+point.getTarget());

	}
	
	@Around(value = "execution(* com.service.*.*Around(..))")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		System.out.println("@Around增强"); 
         System.out.println("模拟执行目标方法前的增强处理：事务开始..."); 
         //修改目标方法的参数 
		Object[] params = point.getArgs();
		if(params!=null){
			if(params.length>0&&params[0].getClass()==String.class){
				params[0] = params[0] + " add";
			}
			if(params.length>1&&params[1].getClass()==String.class){
				params[1] = params[1] + " add";
			}
		}

         //执行目标方法，并保存目标方法执行后的返回值 
		Object returnValue = point.proceed(params);
         System.out.println("模拟执行目标方法后的增强处理：事务结束..."); 
         //返回修改后的返回值 
         return "方法实际返回值：" + returnValue + "，这是返回值的后缀"; 
     } 

}
